﻿using System;
using System.IO;
using System.Net;

namespace MusicStore.Silverlight.Helpers
{
	/// <summary>
	/// used only to upload files in jpg format
	/// </summary>
	public class FileUploader
	{
		public static void UploadFile(int imageId, Stream data, Action callback)
		{
			UriBuilder ub = new UriBuilder("http://localhost.:50671/filereceiver.ashx");
			ub.Query = string.Format("id={0}", imageId);
			WebClient c = new WebClient();
			c.OpenWriteCompleted += (sender, e) =>
			{
				PushData(data, e.Result);
				e.Result.Close();
				data.Close();
				callback();
			};
			c.OpenWriteAsync(ub.Uri);
		}

		private static void PushData(Stream input, Stream output)
		{
			byte[] buffer = new byte[4096];
			int bytesRead;
			while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
			{
				output.Write(buffer, 0, bytesRead);
			}
		}
	}
}
